package net.diaowen.common.base.controller;

import net.diaowen.common.utils.ResultJson;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class SecurityController {

    @RequestMapping("/login.do")
    public String login(HttpServletRequest request,HttpServletResponse response) throws Exception {
        System.out.println("to login");
        return "/login";
    }

    @RequestMapping("/logout.do")
    public String logout(HttpServletRequest request,HttpServletResponse response) throws Exception {
        if (SecurityUtils.getSubject() != null) {
            SecurityUtils.getSubject().logout();
        }
        request.getSession().invalidate();
        return "/login";
    }
    // 定义缓存
    private static final ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<>();

    /*模拟登录token
     */
    @RequestMapping("/monitoken.do")
    @ResponseBody
    public ResultJson  monitoken(HttpServletRequest request) throws Exception {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String uuid = UUID.randomUUID().toString();
        String time = String.valueOf(new Date().getTime());
        String res=uuid + "|"+ username +"|"+ password + "|" +time;
        // 将 res 存储到缓存中
        cache.put(uuid+time, res);
        // 从缓存中读取 res
      /*  String cachedRes = cache.get(time);
        if (cachedRes != null) {
            System.out.println("从缓存中读取的 res: " + cachedRes);
        } else {
            System.out.println("缓存中没有 res");
        }*/
        System.out.println(res);

        Map<String,Object> retMap = new HashMap<>();
        retMap.put("key",uuid);
        retMap.put("tm",time);
        return ResultJson.success(retMap);
    }

    /**
     * 模拟登录
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/monilogin.do")
    public ModelAndView monilogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView();

        String key=request.getParameter("key");
        String tm =request.getParameter("tm");
        String serviceurl =request.getParameter("serviceurl");
        // 从缓存中读取 res
        if(StringUtils.isEmpty(key)|| StringUtils.isEmpty(tm)  ){
            modelAndView.addObject("info","参数不合规");
        }


        String cachedRes = cache.get(key+tm);
        if (cachedRes != null) {
            System.out.println("从缓存中读取的 res111: " + cachedRes);
            String[] usernamepwd = cachedRes.split("\\|");

            // 获取当前用户
            Subject currentUser = SecurityUtils.getSubject();
            // 创建用户令牌，即用户提供的登录信息
            System.out.println("username="+usernamepwd[1]);
            System.out.println("userpwd="+usernamepwd[2]);
            UsernamePasswordToken token = new UsernamePasswordToken(usernamepwd[1], usernamepwd[2]);
            try {
                // 登录，即验证用户名和密码
                currentUser.login(token);
                System.out.println("登录成功");
                modelAndView.addObject("serviceurl",serviceurl);

                modelAndView.addObject("info","自动登录成功");
                String baseUrl = "";
                baseUrl = request.getScheme() +"://" + request.getServerName()
                        + (request.getServerPort() == 80 ? "" : ":" +request.getServerPort())
                        + request.getContextPath();
                modelAndView.addObject("baseUrl", baseUrl);

            } catch (Exception e) {
                // 处理登录失败的情况
                System.out.println("登录失败: " + e.getMessage());
                modelAndView.addObject("info","登录失败");
            }

        } else {
            System.out.println("缓存中没有 res");
            modelAndView.addObject("info","缓存数据为空");
        }
        modelAndView.setViewName("/jump");

        return modelAndView;
    }

}
